#include <QtSql>
#include <QMessageBox>
#include "psqlenumdelegate.h"

psqlenumdelegate::psqlenumdelegate(QString tableName, QSqlDatabase db, QObject *parent):
        QItemDelegate(parent)
{    
    //enum
    QString sql = "select atr.attname nm, typ.typname tp "
                  "from "
                  "pg_attribute atr, "
                  "pg_type typ, "
                  "pg_class cls "
                  "where "
                  "atr.attrelid=cls.oid "
                  "and atr.atttypid=typ.oid "
                  "and cls.relname='%1' "
                  "and typ.typcategory='E'";
    sql = sql.arg(tableName);
    QSqlQuery query(db);
    query.prepare(sql);
    if(query.exec())
    {        
        while(query.next())
        {
            QSqlQueryModel *model = new QSqlQueryModel();
            QString innersql = QString("select getEnumValues('Enum%1')").arg(query.value(query.record().indexOf("tp")).toString());
            model->setQuery(innersql, db);
            enums.insert(query.value(query.record().indexOf("nm")).toString(), model);
        }
    }
    else
        QMessageBox::information(0, "error", query.lastError().text());
//    //fc
//    sql = "select * from getrelation('%1')";
//    sql = sql.arg(tableName);
//    query.prepare(sql);
//    if(query.exec())
//    {
//        while(query.next())
//        {
//            QSqlTableModel *model = new QSqlTableModel();
//            model->setTable(query.value(query.record().indexOf("reltable")).toString());
//            model->select();
//            mRelationModel *mod = new mRelationModel(model,
//                                                     query.value(query.record().indexOf("relpkey")).toString(),
//                                                     query.value(query.record().indexOf("relfield")).toString()
//                                                     );
//            fcs.insert(query.value(query.record().indexOf("basefield")).toString(), mod);
//        }
//    }
}

QWidget *psqlenumdelegate::createEditor(QWidget *parent,
                                        const QStyleOptionViewItem &option,
                                        const QModelIndex &index) const
{
    const QSqlTableModel *tableModel = qobject_cast<const QSqlTableModel *>(index.model());
    QSqlRecord rec = tableModel->record();
    QString fldname = rec.fieldName(index.column());
    if(enums.contains(fldname))
    {
        QComboBox *combo = new QComboBox(parent);
        combo->setModel(enums[fldname]);        
        return combo;
    }

    const QSqlRelationalTableModel *sqlModel = qobject_cast<const QSqlRelationalTableModel *>(index.model());
    QSqlTableModel *childModel = sqlModel ? sqlModel->relationModel(index.column()) : 0;
    if (childModel)
    {
        QComboBox *combo = new QComboBox(parent);
        combo->setModel(childModel);
        combo->setModelColumn(childModel->fieldIndex(sqlModel->relation(index.column()).displayColumn()));
        return combo;
    }
    return QItemDelegate::createEditor(parent, option, index);
}

void psqlenumdelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    const QSqlTableModel *sqlModel = qobject_cast<const QSqlTableModel *>(index.model());
    QComboBox *combo = qobject_cast<QComboBox *>(editor);
    if (!sqlModel || !combo) {
        QItemDelegate::setEditorData(editor, index);
        return;
    }
    combo->setCurrentIndex(combo->findText(sqlModel->data(index).toString()));
}

void psqlenumdelegate::setModelData(QWidget *editor,
                                    QAbstractItemModel *model,
                                    const QModelIndex &index) const
{
    if (!index.isValid())
        return;
    QSqlRelationalTableModel *sqlModel = qobject_cast<QSqlRelationalTableModel *>(model);
    QString fldname = sqlModel->record().fieldName(index.column());
    QSqlQueryModel *childModel;

    QComboBox *combo = qobject_cast<QComboBox *>(editor);

    if (sqlModel && combo)
    {
        int currentItem = combo->currentIndex();
        int displayIndex = -1;
        int editIndex = -1;
        if(enums.contains(fldname))
        {
            childModel = enums[fldname];
            displayIndex = 0;
            editIndex = 0;
        }
        else
        {
            QSqlTableModel *childTableModel = sqlModel->relationModel(index.column());
            displayIndex = childTableModel->fieldIndex(sqlModel->relation(index.column()).displayColumn());
            editIndex = childTableModel->fieldIndex(sqlModel->relation(index.column()).indexColumn());
            childModel = childTableModel;
        }
        if(childModel)
        {
            sqlModel->setData(index,
                              childModel->data(childModel->index(currentItem, displayIndex), Qt::DisplayRole),
                              Qt::DisplayRole);
            sqlModel->setData(index,
                              childModel->data(childModel->index(currentItem, editIndex), Qt::EditRole),
                              Qt::EditRole);
            return;
        }
    }
    QItemDelegate::setModelData(editor, model, index);
}
